/**
 * jQuery Sina Emotion
 * @author [Jealous](http://www.clanfei.com/)
 * @license MIT
 */
(function ($, window, document, undefined) {
    'use strict';

    var $target;
    var options;
    var emotions = {};
    var categories = [];
    var emotionsMap = {};
    var defCategory = '默认';
    var initialized = false;
    var data = require("./cmt/emotion.json");


    function mapData(data) {

        if (window.emotionsMap) {
            return window.emotionsMap;
        }
        for (var i = 0, l = data.length; i < l; ++i) {
            var item = data[i];
            var category = item['category'] || defCategory;

            if (!emotions[category]) {
                emotions[category] = [];
                categories.push(category);
            }

            emotions[category].push({
                icon: item['icon'],
                phrase: item['phrase']
            });

            emotionsMap[item['phrase']] = item.icon;
        }

        window.emotionsMap = emotionsMap;
    }

    function init() {
        if (initialized) {
            return;
        }

        var $sinaEmotion = $('<div id="sina-emotion">' +
            '<div class="switch">' +
            '<a href="#" class="prev">&laquo;</a>' +
            '<a href="#" class="next">&raquo;</a>' +
            '</div>' +
            '<ul class="categories"></ul>' +
            '<ul class="faces"></ul>' +
            '<ul class="pages"></ul>' +
            '</div>');

        mapData(data);

        if (categories.length <= 5) {
            $sinaEmotion.children('.switch').remove();
        }

        $('body').append($sinaEmotion);
        initEvents();
        options = $.fn.sinaEmotion.options;
        initialized = true;
    }

    function initEvents() {
        var $sinaEmotion = $('#sina-emotion');

        $('body').bind({
            click: function () {
                $sinaEmotion.hide();
            }
        });
        $sinaEmotion.bind({
            click: function (event) {
                event.stopPropagation();
            }
        }).delegate('.prev', {
            click: function (event) {
                var page = $sinaEmotion.find('.categories').data('page');
                showCatPage(page - 1);
                event.preventDefault();
            }
        }).delegate('.next', {
            click: function (event) {
                var page = $sinaEmotion.find('.categories').data('page');
                showCatPage(page + 1);
                event.preventDefault();
            }
        }).delegate('.category', {
            click: function (event) {
                $sinaEmotion.find('.categories .current').removeClass('current');
                showCategory($.trim($(this).addClass('current').text()));
                event.preventDefault();
            }
        }).delegate('.page', {
            click: function (event) {
                $sinaEmotion.find('.pages .current').removeClass('current');
                var page = parseInt($(this).addClass('current').text(), 10) - 1;
                showFacePage(page);
                event.preventDefault();
            }
        }).delegate('.face', {
            click: function (event) {
                $sinaEmotion.hide();
                $target.insertText($(this).children('img').prop('alt')).focus();
                event.preventDefault();
            }
        });
    }

    function showCatPage(page) {
        var html = '';
        var length = categories.length;
        var maxPage = Math.ceil(length / 5);
        var $categories = $('#sina-emotion').find('.categories');
        var category = $categories.data('category') || defCategory;

        page = (page + maxPage) % maxPage;

        for (var i = page * 5; i < length && i < (page + 1) * 5; ++i) {
            html += '<li class="item">' +
                '<a href="#" class="category' + (category === categories[i] ? ' current' : '') + '">' + categories[i] + '</a>' +
                '</li>';
        }

        $categories.data('page', page).html(html);
    }

    function showCategory(category) {
        $('#sina-emotion').find('.categories').data('category', category);
        showFacePage(0);
        showPages();
    }

    function showFacePage(page) {
        var html = '';
        var pageSize = options.pageSize;
        var $sinaEmotion = $('#sina-emotion');
        var category = $sinaEmotion.find('.categories').data('category');
        var faces = emotions[category];
        page = page || 0;

        for (var i = page * pageSize, l = faces.length; i < l && i < (page + 1) * pageSize; ++i) {
            var face = faces[i];
            var icon = face['icon'].replace('http://', '//');
            var phrase = face['phrase'];
            html += '<li class="item">' +
                '<a href="#" class="face">' +
                '<img class="sina-emotion" src="' + icon + '" title="' + phrase + '" alt="' + phrase + '" /><span><i>' + phrase + '</i></span>' +
                '</a>' +
                '</li>';
        }

        $sinaEmotion.find('.faces').html(html);
    }

    function showPages() {
        var html = '';
        var pageSize = options.pageSize;
        var $sinaEmotion = $('#sina-emotion');
        var category = $sinaEmotion.find('.categories').data('category');
        var faces = emotions[category];
        var length = faces.length;

        if (length > pageSize) {
            for (var i = 0, l = Math.ceil(length / pageSize); i < l; ++i) {
                html += '<li class="item">' +
                    '<a href="#" class="page' + (i === 0 ? ' current' : '') + '">' + (i + 1) + '</a>' +
                    '</li>';
            }
            $sinaEmotion.find('.pages').html(html).show();
        } else {
            $sinaEmotion.find('.pages').hide();
        }
    }

    /**
     * 为某个元素设置点击事件，点击弹出表情选择窗口
     * @param  {String|function} target 用于插入表情文本框选择器，或返回文本框 jQuery 对象的方法
     */
    $.fn.sinaEmotion = function (target) {
        var $this = $(this).last();
        var offset = $this.offset();

        target = target || function () {
            return $this.parents('form').find('textarea, input[type=text]').eq(0);
        };

        if ($this.is(':visible')) {
            if (typeof target === 'function') {
                $target = target.call($this);
            } else {
                $target = $(target);
            }

            init();
            showCategory(defCategory);
            showCatPage(0);

            console.log(offset,offset.top,(window.outerHeight-385),window.outerHeight,window.outerHeight-385);

            $('#sina-emotion').css({
                position:offset.top<(window.outerHeight-385)?'absolute':'fixed',
                top: offset.top<(window.outerHeight-385)?offset.top:(window.outerHeight-385),
                left: offset.left - 55
            });

            setTimeout(function () {
                $('#sina-emotion').show();
            }, 100)

        }


        return this;
    };

    window.parseEmotionContent = function (html) {
        mapData(data);
        html = html.replace(/<[\s\S]*?>/g, function ($1) {
            $1 = $1.replace('[', '&#91;');
            $1 = $1.replace(']', '&#93;');
            return $1;
        }).replace(/\[[^\[\]]*?]/g, function ($1) {

            if ($1.indexOf('IMG:') > -1) {
                //这里是图片
                var src = $1.replace('[IMG:', ''), src = src.replace(']', '');
                // console.log(src)
                return '<img class="lazyload"  src="" data-src="' + util.cdn(src) + '"  />';
            }


            if ($1.indexOf('AUDIO:') > -1) {
                //这里是图片
                var src = $1.replace('[AUDIO:', ''), src = src.replace(']', '');
                // console.log(src)
                return '<audio src="' + util.cdn(src) + '" controls  >  浏览器不支持音频播放</audio> ';
            }

            if (typeof window['emotionsMap'][$1] == "undefined") {
                return $1;
            }

            var url = window['emotionsMap'][$1].replace('http://', '//');
            if (url) {
                return '<img class="sina-emotion lazyload"  src="" data-src="' + url + '" title="' + $1 + '" />';
            }
            return $1;
        });

        return html;
    }


    $.fn.parseEmotion = function () {
        init();
        $(this).each(function () {
            var $this = $(this);
            var html = $this.html();

            html = parseEmotionContent(html);

            $this.html(html);
        });
        return this;
    };

    $.fn.insertText = function (text) {

        console.log(text);
        this.each(function () {
            if (this.tagName !== 'INPUT' && this.tagName !== 'TEXTAREA') {
                return;
            }
            if (document.selection) {
                this.focus();
                var cr = document.selection.createRange();
                cr.text = text;
                cr.collapse();
                cr.select();
            } else if (this.selectionStart !== undefined) {
                var start = this.selectionStart;
                var end = this.selectionEnd;
                this.value = this.value.substring(0, start) + text + this.value.substring(end, this.value.length);
                this.selectionStart = this.selectionEnd = start + text.length;
            } else {
                this.value += text;
            }

            var evt = document.createEvent('UIEvents');
            evt.initUIEvent("input", true, true, window, 1);
            this.dispatchEvent(evt);
        });

        return this;
    };

    $.fn.sinaEmotion.options = {
        pageSize: 35, // 每页显示的表情数
    };
})(jQuery, window, document);
